package org.jeecg.zhenxuan.AOP;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.jeecg.zhenxuan.Repository.AccessInterfaceIPListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class AccessInterfaceSecurityAop {


    private ThreadLocal<Boolean> booleanThreadLocal = new ThreadLocal<>();

    @Autowired
    private AccessInterfaceIPListRepository accessInterfaceIPListRepository;

    @Pointcut(value = "execution(* org.jeecg.zhenxuan.Controller.PointTradingStdController.*(..)))")
    public void InterfaceAccessPointcut(){}



    /**
     * 带参 关注点对象 处理JWT
     * 需要把jwt放在最后一个参数
     * @param proceedingJoinPoint
     * @return
     */
    @Around(value = "InterfaceAccessPointcut()")
    public Object oneParamBeforeHandlerByAnnoWithParam2(ProceedingJoinPoint proceedingJoinPoint ){

        log.info("$$$$$$$$$$$$$$$$$$$$$$ 注解切点 抓取关注点参数 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
        log.info("Come in Aop Procduce : "+ "powerd by annotation" + " JoinPoint");

        booleanThreadLocal.set(new Boolean(false));

        HttpServletRequest request = (HttpServletRequest) proceedingJoinPoint.getArgs()[proceedingJoinPoint.getArgs().length - 1 ];

        if (request == null) {
            JSONObject result = new JSONObject();
            result.put("status", "500");
            result.put("message", "没有request");
            return result;
        }else {


            accessInterfaceIPListRepository.findAll().forEach(i->{
                if (request.getRemoteAddr().equals(i.getIP())) {
//                    semaphore = true;

                    booleanThreadLocal.set(true);
                }
            });

            if (!booleanThreadLocal.get()) {
                JSONObject result = new JSONObject();
                result.put("status", "401");
                result.put("message", "白名单没有配置！《"+request.getRemoteAddr()+"》");


                return result;
            }

        }



        log.info("$$$$$$$$$$$$$$$$$$$$$$ 注解切点 抓取关注点参数 $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");

        try {
            Object result = proceedingJoinPoint.proceed();
            log.info(result.toString());
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}
